package com.cskaoyan.controller.admincontroller;

import com.cskaoyan.bean.chaosbean.auth.vo.DashBoardDataVO;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.po.AdminInfoBean;
import com.cskaoyan.bean.po.InfoData;
import com.cskaoyan.bean.po.LoginUserData;
import com.cskaoyan.bean.po.MarketAdmin;
import com.cskaoyan.shiro.MarketToken;
import com.cskaoyan.exception.ValidationException;
import com.cskaoyan.service.adminservice.AuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
/**
 * @author 楚夏三分
 * @datetime 2023/1/1 16:29
 * @description: TODO: 认证及鉴权, 本层代码极不规范, 几乎都在Controller层, 请自行优化, 我歇菜了
 * TODO: 邢中凯大傻逼
 */
@RestController
@RequestMapping("admin")
public class AuthController {
    @Autowired
    private AuthService authService;

    /**
     * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @PostMapping("auth/login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        // 执行登录
        // 此处subject作为局部变量
        // subject线程安全, 但每个用户对应单独的subject
        Subject subject = SecurityUtils.getSubject();
        // 认证
        UsernamePasswordToken authenticationToken = new MarketToken(username, password,"admin");
        try {
            subject.login(authenticationToken);
        } catch (AuthenticationException e){
            e.printStackTrace();
            return BaseRespVo.err();
        }

        // 判断是否认证成功
        boolean authenticated = subject.isAuthenticated();


        // 写业务
        MarketAdmin marketAdmin = (MarketAdmin) subject.getPrincipal();
        LoginUserData loginUserData = new LoginUserData();

        AdminInfoBean adminInfo = new AdminInfoBean();
        // adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminInfo.setAvatar(marketAdmin.getAvatar());
        // adminInfo.setNickName("admin123");
        adminInfo.setNickName(marketAdmin.getUsername());
        loginUserData.setAdminInfo(adminInfo);

        // 此处原为死代码, 将客户端携带的SessionID值写死
        // loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        // 改为从Session中获取,并将其
        // 获得Session信息
        Session session = subject.getSession();
        loginUserData.setToken((String) session.getId());
        return BaseRespVo.okYa(loginUserData);
    }

    /**
     * TODO: 获取当前登录用户的相关信息
     * @param token
     * @return
     * @throws ValidationException
     */
    @RequestMapping("auth/info")
    public BaseRespVo info(String token) throws ValidationException {
        //
        //
        // //开发完shiro之后，再整合
        // InfoData infoData = new InfoData();
        // infoData.setName("admin123");
        //
        // //根据primaryPrincipal做查询
        // infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        // ArrayList<String> roles = new ArrayList<>();
        // roles.add("超级管理员");
        // infoData.setRoles(roles);
        // ArrayList<String> perms = new ArrayList<>();
        // perms.add("*");
        // infoData.setPerms(perms);
        // return BaseRespVo.ok(infoData);


        if (token == null || "".equals(token)) {
                throw new ValidationException("存在空参数");
            }

        //整合shiro
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return BaseRespVo.unAuthc();
        }

        //开发完shiro之后，再整合

        // 查询
        MarketAdmin marketAdmin = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
        String username = marketAdmin.getUsername();

        AdminInfoBean infoBean = authService.getAdminInfo(username);

        InfoData infoData = new InfoData();
        infoData.setName(infoBean.getNickName());
        infoData.setAvatar(infoBean.getAvatar());

        List<String> roles = authService.getAdminRoles(username);
        infoData.setRoles(roles);

        List<String> perms = authService.getAdminPerms(username);

        infoData.setPerms(perms);
        return BaseRespVo.ok(infoData);
    }

    @RequestMapping("auth/401")
    public BaseRespVo loginFail() {
        return BaseRespVo.unAuthc();
    }

    @PostMapping("auth/logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok(0);
    }


    @GetMapping("dashboard")
    public BaseRespVo<DashBoardDataVO> dashBoard() {
        DashBoardDataVO data = authService.getDashBoardData();
        return BaseRespVo.ok(data);
    }
}
